﻿namespace Eldert.BTUG.IoT.Device.RaspberryPi2
{
    using System;
    using System.Diagnostics;
    using System.Text;
    using System.Threading.Tasks;

    using Data.Engine;

    using Microsoft.Azure.Devices.Client;

    using Newtonsoft.Json;

    /// <summary>
    /// Proxy class used to communicate with IoT Hub.
    /// </summary>
    internal class IoTHubProxy
    {
        // TODO: Use your own settings here.

        /// <summary>
        /// Device client used to connect to IoT Hub.
        /// </summary>
        private static readonly DeviceClient deviceClient = DeviceClient.Create(
            "your-host-name",
            new DeviceAuthenticationWithRegistrySymmetricKey("your-device-id", "your-device-key"));

        /// <summary>
        /// Send message to IoT Hub.
        /// </summary>
        /// <param name="engineReadings">
        /// The engine readings to be sent.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        internal static async Task Send(EngineReadings engineReadings)
        {
            await deviceClient.SendEventAsync(new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(engineReadings))));
        }

        /// <summary>
        /// Receive message from IoT Hub.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        internal static async Task<string> Receive()
        {
            // Get the message
            var message = await deviceClient.ReceiveAsync();

            // Check if a valid message was received
            if (message == null)
            {
                return null;
            }

            // Get the string in the message
            var messageString = Encoding.ASCII.GetString(message.GetBytes());

            // Console info
            Debug.WriteLine(messageString);

            // Finish receive of the message
            await deviceClient.CompleteAsync(message);

            // Return the string in the message
            return messageString;
        }
    }
}
